using UnityEngine;
using Yoozoo.Managers.ResourceManagerV2.Runtime;

namespace WorldMapBase.Tile.Pool
{
    public class DynamicPrefabPool: ObjectPool<Transform>
    {
        private int _initNum;
        protected GameObject _originObject;
        private bool isUI = false;

        public DynamicPrefabPool(int initNum, int capacity, GameObject originObject) : 
            base(capacity,true,1,5,10)
        {
#if UNITY_EDITOR
            _name = "沙盘动态层对象池: " + originObject.name;
#endif
            
            _initNum = initNum;
            _originObject = originObject;
            var canvasGroup = originObject.GetComponent<CanvasGroup>();
            isUI = canvasGroup != null;
            if(isUI)
                canvasGroup.alpha = 0;
        }


        public void PreInit()
        {
            OnInit(_initNum);
        }
        
        protected override Transform ConstructItem()
        {
            if (_originObject == null)
            {
                UnityEngine.Debug.LogError("DynamicPrefabPool ConstructItem _originObject is nil");
                return null;
            }
            
            Transform objTransform = 
                GameObject.Instantiate(_originObject, GlobalValue.INVISIBLE_POSITION, Quaternion.identity,WorldDynamicPoolMgr.InstanceRoot).transform;
            
            return objTransform;
        }

        protected override void OnGetObject(Transform obj)
        {
            base.OnGetObject(obj);
            if (isUI)
            {
                var canvasGroup = obj.GetComponent<CanvasGroup>();
                canvasGroup.alpha = 1;
            }
        }

        protected override void BeforeRecover(Transform obj)
        {
            obj.position = GlobalValue.INVISIBLE_POSITION;
            if (isUI)
            {
                var canvasGroup = obj.GetComponent<CanvasGroup>();
                canvasGroup.alpha = 0;
            }
        }

        protected override void OnRemoveItem(Transform trans)
        {
            GameObject.Destroy(trans.gameObject);
        }

        public override void Destroy()
        {
            base.Destroy();
            _originObject = null;
        }
    }
}